#include "stdafx.h"
#include "MainWindow.h"
#include "ui_MainWindow.h"
#include "SQLConnection.h"
#include "SimulationThread.h"
#include "PrintThread.h"

using namespace std;
using namespace AirCrash::Calypso;

MainWindow::MainWindow(QWidget *parent, Qt::WFlags flags) : QMainWindow(parent, flags), mUi(new Ui::MainWindowClass()), 
		mSimThread(0), mPrintDialog(this), mPrintThread(0), mProgressBar(0), mExportImportThread(0) {

	mUi->setupUi(this);

	if (Config::get("Settings", "hideMouse").toBool()) {
		mUi->mTombolaPage->setCursor( QCursor( Qt::BlankCursor ) );
	}

	if (!SQLConnection::createDB()) {
		mUi->mTombolaPage->setBlocked(true);
	}

	mUi->mInsertMenu->setEnabled(false);
	mUi->mConfigMenu->setEnabled(false);

	mUi->mPrevCode->setImages("Image", "previousButton");
	mUi->mNextCode->setImages("Image", "nextButton");

	float scale(rect().height() / 1024.f);

	connect( mUi->mDeleteLast, SIGNAL(triggered()), mUi->mTombolaPage, SLOT(deleteLast()) );

	///Set the current widget and the ui on the pages.
	mUi->mPages->setCurrentWidget(mUi->mTombolaPage);
	mUi->mTombolaPage->setUi(mUi, scale);
	mUi->mInsertPage->setUi(mUi);
	mUi->mStaticsPage->setUi(mUi);
	mUi->mDatabasePage->setUi(mUi);
	mUi->mConfigPage->setUi(mUi);
	mUi->mNumpadWidget->scale(scale);

	if (Config::get("Settings", "fullScreen").toBool()) {
		this->showFullScreen();
	}

	if (Config::get("Settings", "allowShutdown").toBool()) {
		mUi->mShutdown->setEnabled(true);
	} else {
		mUi->mShutdown->setEnabled(false);
	}

	if (Config::get("Settings", "webcamEnabled").toBool()) {
		mUi->mImages->setVisible(false);
		mUi->mOpenCvWidget->setVisible(true);
	} else {
		mUi->mImages->setVisible(true);
		mUi->mOpenCvWidget->setVisible(false);
	}

	if (Config::get("Simulation", "enabled").toBool()) {
		mSimThread = new SimulationThread();
		connect( mSimThread, SIGNAL(changePage(int)), this, SLOT(changePage(int)) );
		connect( mSimThread, SIGNAL(fillInsertPage(int, int, int, QString, bool)), mUi->mInsertPage, SLOT(fillInsertPage(int, int, int, QString, bool)) );
		connect( mSimThread, SIGNAL(createItem()), mUi->mInsertPage, SLOT(createItem()) );
		connect( mSimThread, SIGNAL(generateCodes()), mUi->mInsertPage, SLOT(generateCodes()) );
		connect( mUi->mInsertPage, SIGNAL(nextItem()), mSimThread, SLOT(nextItem()) );
		connect( mSimThread, SIGNAL(enterCode(const QString&)), mUi->mTombolaPage, SLOT(numpadInsert(const QString&)) );
		connect( mSimThread, SIGNAL(getCode()), mUi->mTombolaPage, SLOT(numpadGetCode()) );
		mSimThread->start();
	}

	mPrintThread = new PrintThread();
	connect( mPrintThread, SIGNAL(finished()), this, SLOT(printDone()) );

	mProgressBar = new QProgressBar();
	mProgressBar->setWindowModality(Qt::ApplicationModal);
	mExportImportThread = new ExportImportThread();
	connect( mExportImportThread, SIGNAL(updateProgress(int)), mProgressBar, SLOT(setValue(int)) );
	mProgressBar->setValue(0);
}

MainWindow::~MainWindow() {
	if (mSimThread) {
		mSimThread->interrupt();
		mSimThread->wait();
		delete mSimThread;
	}
	
	mPrintThread->wait();
	delete mPrintThread;

	mProgressBar->hide();
	delete mProgressBar;

	SQLConnection::destroyDB();
	delete mUi;
}

void MainWindow::changePage() {
	if (QObject::sender() == mUi->mTombola) {
		mUi->mPages->setCurrentWidget(mUi->mTombolaPage);
	}
	if (QObject::sender() == mUi->mInsert) {
		mUi->mPages->setCurrentWidget(mUi->mInsertPage);
	}
	if (QObject::sender() == mUi->mStats) {
		mUi->mPages->setCurrentWidget(mUi->mStaticsPage);
	}
	if (QObject::sender() == mUi->mDatabase) {
		mUi->mPages->setCurrentWidget(mUi->mDatabasePage);
	}
	if (QObject::sender() == mUi->mConfig) {
		mUi->mPages->setCurrentWidget(mUi->mConfigPage);
	}
}

void MainWindow::shutdown() {
	QMessageBox shutdownBox;
	shutdownBox.setText("Computer afsluiten?");
	shutdownBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
	shutdownBox.setDefaultButton(QMessageBox::No);
	int chosenButton = shutdownBox.exec();
	if (chosenButton == QMessageBox::Yes) {
		QProcess shutdownProcess;
#ifdef WIN32
		shutdownProcess.execute("shutdown /s /t 1");
#else
		shutdownProcess.execute("/sbin/poweroff -h now");
#endif
	}
}

void MainWindow::print() {
	if (!mPrintThread->isRunning() && mPrintDialog.exec() == QDialog::Accepted) {
		mPrintThread->setPrinter(mPrintDialog.printer());
		mPrintThread->setPrintType(PrintType::Items);
		mUi->mPrint->setEnabled(false);
		mPrintThread->start();
	}
}

void MainWindow::printDone() {
	mUi->mPrint->setEnabled(true);
}

void MainWindow::resizeEvent(QResizeEvent * e) {
	float scale(rect().height() / 1024.f);
	mUi->mTombolaPage->setUi(mUi, scale);
	mUi->mNumpadWidget->scale(scale);
	mUi->mStaticsPage->setUi(mUi);
}

void MainWindow::changePage(int page) {
	if (page == 1) {
		mUi->mTombola->activate(QAction::Trigger);
	} else {
		mUi->mInsert->activate(QAction::Trigger);
	}
}

void MainWindow::exportDB() {
	mProgressBar->setValue(0);		
	mProgressBar->show();
	mExportImportThread->exportDb();
}

void MainWindow::importDB() {
}

namespace AirCrash {
namespace Calypso {

ExportImportThread::ExportImportThread() {
}

ExportImportThread::~ExportImportThread() {
}

void ExportImportThread::run() {
	if (isExport) {
		QDir exportDir("export");
		if (exportDir.exists()) {
			QStringList files(exportDir.entryList(QDir::Files));
			foreach (QString fileName, files) {
				exportDir.remove(fileName);
			}
		} else {
			QDir(".").mkdir("export");
			QDir("export").mkdir("items");
		}

		QSqlQuery total("SELECT COUNT(Id) FROM Items");
		total.first();
		int totalItems(total.value(0).toInt());

		QSqlQuery query("SELECT * FROM Items");

		QFile items("export/items.cvs");
		items.open(QIODevice::WriteOnly | QIODevice::Text);
		QTextStream stream(&items);
	
		int numItem(0);
		while (query.next()) {
			++numItem;
			stream << query.value(0).toString() << ";" << query.value(1).toString() << ";" << query.value(0).toString() << ".png;" 
				<< query.value(3).toString() << ";" << query.value(4).toString()  << ";" << query.value(5).toString() << ";" 
				<< query.value(6).toString() << ";" << query.value(7).toString() << "\n";
			QByteArray imageData = query.value(2).toByteArray();
			QImage img = QImage::fromData(imageData, "PNG");
			img.save("export/items/" + query.value(0).toString() + ".png");
			emit updateProgress((numItem / float(totalItems)) * 100);
		}

		items.close();
	}
}

void ExportImportThread::importDb() {
	isExport = false;
	start();
}

void ExportImportThread::exportDb() {
	isExport = true;
	start();
}

}
}